package com.snail.readyvr.rest;

import com.snail.readyvr.application.MyApplication;
import com.snail.readyvr.event.GetSessionEvent;
import com.snail.readyvr.mvp.model.ReportParam;
import com.snail.readyvr.mvp.model.ReportResponse;
import com.snail.readyvr.util.AppUtils;
import com.snail.readyvr.util.Constant;
import com.snail.readyvr.util.EventBus;
import com.snail.readyvr.util.LogUtils;
import com.snail.readyvr.util.StringUtils;
import com.snail.readyvr.util.Utils;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by MRKING on 2016/11/7.
 */

public class GetSessionUtils {

    private GetSessionUtils() {
    }

    /**
     * 未使用注入，可以这样获取RestClient
     * ((MyApplication)MyApplication.getmContext())
     * .getApplicationComponent()
     * .getRestClient()
     *
     * @param restClient
     * @param from
     */
    public static void getSession(RestClient restClient, int from) {
        final GetSessionEvent sessionEvent = new GetSessionEvent();
        sessionEvent.setFrom(from);
        ReportParam reportParam = new ReportParam();
        reportParam.setUuid(AppUtils.getWIFIMac(MyApplication.getmContext()));
        reportParam.setHardware_ver(AppUtils.getInfo());
        reportParam.setOpersys_ver("Android " + AppUtils.getVersionRelease());

        restClient.report(reportParam)
                  .map(new HttpResultFunc<ReportResponse>(RestApiUtils.GET_SESSION_ID_API))
                  .subscribeOn(Schedulers.io())
                  .observeOn(AndroidSchedulers.mainThread())
                  .subscribe(new Subscriber<ReportResponse>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        faile();
                    }

                    private void faile() {
                        sessionEvent.setType(GetSessionEvent.TYPE_FAILE);
                        EventBus.getDefault().post(Constant.BusTag.GET_SESSIONID_TAG, sessionEvent);
                    }

                    @Override
                    public void onNext(ReportResponse reportResponse) {
                        if (reportResponse != null && !StringUtils.isBlank(reportResponse.getSessionid())) {
                            Utils.sessionid = reportResponse.getSessionid();
                            LogUtils.d("seesionid-->" + Utils.sessionid);
                            sessionEvent.setType(GetSessionEvent.TYPE_SUCCESS);
                            EventBus.getDefault().post(Constant.BusTag.GET_SESSIONID_TAG, sessionEvent);
                        } else {
                            faile();
                        }

                    }
                });
    }
}
